#include "mainwindow.h"
#include <QNetworkInterface>
#include <QHostInfo>
#include <QThread>
#include <QDebug>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setGeometry(0, 0, 800, 480);
    mPushButton[0] = new QPushButton();
    mPushButton[0]->setText("获取本机信息");
    mPushButton[0]->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    mPushButton[1] = new QPushButton();
    mPushButton[1]->setText("清空文本信息");
    mPushButton[1]->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);

    mTextBrowser = new QTextBrowser();/* 文本浏览框用于显示本机信息 */
    hWidget = new QWidget();
    vWidget = new QWidget();
    vBoxLayout = new QVBoxLayout();
    hBoxLayout = new QHBoxLayout();

    hBoxLayout->addWidget(mPushButton[0]);
    hBoxLayout->addWidget(mPushButton[1]);
    hWidget->setLayout(hBoxLayout);

    vBoxLayout->addWidget(mTextBrowser);
    vBoxLayout->addWidget(hWidget);
    vWidget->setLayout(vBoxLayout);

    setCentralWidget(vWidget);

    timer = new QTimer();

    connect(mPushButton[0], &QPushButton::clicked, this, &MainWindow::showHostInfo);
    connect(mPushButton[1], &QPushButton::clicked, this, &MainWindow::clearHostInfo);
    connect(timer, &QTimer::timeout, this, &MainWindow::timerTimeOut);
}

MainWindow::~MainWindow()
{
    delete timer;
}

QString MainWindow::getHostInfo()
{
    QString str = "主机名称：" + QHostInfo::localHostName() + "\n";

    /* 获取所有的网络接口 */
    QList<QNetworkInterface> list = QNetworkInterface::allInterfaces();
    foreach (auto& interface, list) {
        str += "网卡设备：" + interface.name() + "\n";
        str += "MAC地址：" + interface.hardwareAddress() + "\n";

        QList<QNetworkAddressEntry> entryList = interface.addressEntries();
        foreach(auto& entry, entryList) {
            if (entry.ip().protocol() == QAbstractSocket::IPv4Protocol) {
                str += "IP地址：" + entry.ip().toString() + "\n";
                str += "子网掩码：" + entry.netmask().toString() + "\n";
                str += "广播地址：" + entry.broadcast().toString() + "\n\n";
            }
        }
    }
    return str;
}

void MainWindow::timerTimeOut()
{
    showHostInfo();
    timer->stop();
}

void MainWindow::showHostInfo()
{
    mTextBrowser->insertPlainText(getHostInfo());
}

void MainWindow::timerStart()
{
    mTextBrowser->clear();
    timer->start(1000);
}

void MainWindow::clearHostInfo()
{
    if (!mTextBrowser->toPlainText().isEmpty()) {
        mTextBrowser->clear();
    }
}
